package com.cc.service

import com.cc.common.exception.ServerException
import com.cc.mapper.UserMapper
import com.cc.model.User
import com.cc.model.convert.UserConvert
import com.cc.model.dto.UserDto
import com.mybatisflex.core.paginate.Page
import com.mybatisflex.core.query.QueryWrapper
import org.springframework.stereotype.Service

/**
 * @author cc
 * @since 2024/4/21
 * @version 1.0
 */
@Service
class UserService(
    private val userMapper: UserMapper, private val userConvert: UserConvert,
) {

    fun create(user: User) {
        userMapper.insert(user)
    }

    fun delete(id: String) {
        try {
            userMapper.selectOneById(id).apply {
                check("admin" != account) {
                    throw ServerException("无法删除管理员账户")
                }.let {
                    userMapper.deleteById(id)
                }
            }
        } catch (ex: Exception) {
            throw ServerException("用户不存在")
        }
    }

    fun deleteBatch(ids: List<String>) {
        check(ids.isNotEmpty()) {
            throw ServerException("请选择用户")
        }.let {
            userMapper.selectListByIds(ids).filter { "admin" != it.account }.let {
                userMapper.deleteBatchByIds(ids)
            }
        }
    }

    fun update(user: User) {
        create(user)
    }

    fun findAll(page: Int, num: Int): Page<UserDto> {

        return userMapper.paginate(Page.of(page, num), QueryWrapper.create()).map {
            userConvert.toDto(it)
        }
    }

    fun getUserDetail(id: String) = try {
        userMapper.selectOneById(id).let {
            userConvert.toDto(it)
        }
    } catch (ex: Exception) {
        throw ServerException("用户信息不存在")
    }

    fun getUserByAccount(account: String): UserDto {
        return userMapper.selectOneByQuery(QueryWrapper.create()).let {
            userConvert.toDto(it)
        }
    }


}